//
const { getByCode } = require('../../model/project')
const { ProjectCodeNotExistErr } = require('../../response/code')
const redis = require('../../util/redis')

const { PROJECT_CODE_PREFIX } = require('../../consts/system')

// 项目code转id
const projCode2Id = async (ctx, next) => {
  try {
    const projId = await getCode2Id(ctx)
    console.log(projId, '<<< projId')
    if (!projId) {
      return ctx.app.emit('error', ProjectCodeNotExistErr, ctx)
    }
    ctx.state.project_id = +projId
    return next()
  } catch (e) {
  } finally {
    ctx.state.project_id = null
  }
}

const getCode2Id = async (ctx) => {
  const header = ctx.request.header
  // 取得token信息
  const projCode = header['code'] ? header['code'] : ''
  if (!projCode || projCode === '') {
    ctx.app.emit('error', ProjectCodeNotExistErr, ctx)
    return null
  }
  const sysUserId = ctx.state.user.id
  const conn = await redis.connect()
  //
  let projId = await conn.get(`${PROJECT_CODE_PREFIX}:${sysUserId}:${projCode}`)
  // 判断 code是否存在
  if (!projId) {
    // TODO 这里需要做防刷处理
    const where = {
      sys_user_id: sysUserId,
    }
    // 查找数据,如果没有找到则返回错误
    const proj = await getByCode(projCode, where)
    if (!proj) return null

    projId = proj.id
    // 保存到redis
    await conn.set(`${PROJECT_CODE_PREFIX}:${sysUserId}:${projCode}`, projId)
    // 保存并进入下一步
  }
  await conn.close()
  return projId
}

module.exports = {
  projCode2Id,
}
